import { computed, onMounted, ref, watch } from "vue";
import { MessageUtil } from "@/utils/messageUtil";
import { cloneDeep } from "lodash-es";

export const selectProps = {
  value: {
    type: [Object],
    default: () => []
  },
  table: {
    type: Object,
    default: () => {}
  },
  multiple: {
    type: Boolean,
    default: false
  },
  // 选择校验规则
  columnSelectedCountRule: {
    type: Object,
    default: () => {}
  }
};

export const selectEmit = ["change", "update:value"];

export function useMatrixSelect(props: any, emit: any) {
  //  // 矩阵单选默认数据结构 {"1":"选项1","2":"选项1","3":"选项1","1636537741435":"选项1"}
  //       // 矩阵多选默认数据结构 {"1":["选项1","选项2","选项3"],"2":["选项1","选项2","选项3"],"3":["选项1","选项2","选项3"]}
  const dataValue = ref<Record<string, any>>({});
  const oldDataValue = ref<Record<string, any>>({});

  const initValue = (val: any) => {
    let initVal: Record<string, any> = {};
    let cloneVal = cloneDeep(val);
    if (props.multiple) {
      props.table.rows.forEach((row: any) => {
        if (cloneVal[row.id]) {
          initVal[row.id] = cloneVal[row.id];
        } else {
          initVal[row.id] = [];
        }
      });
    } else {
      initVal = cloneVal || {};
    }
    dataValue.value = initVal;
  };

  const handleChange = (val: string, rowId: string) => {
    // 移动端初始化时的空值处理
    if (!val || !Object.keys(val).length) {
      return;
    }

    // 验证选择数量
    if (props.columnSelectedCountRule) {
      const colId = props.table.columns.find((item: any) => item.label === val)?.id;
      const maxCount = colId ? props.columnSelectedCountRule[colId] : null;

      if (maxCount) {
        const currentCount = Object.values(dataValue.value).filter(item => item === val).length;

        if (currentCount > maxCount) {
          // 超出最大选择数量，恢复为旧值
          dataValue.value[rowId] = oldDataValue.value[rowId];
          MessageUtil.error(`${val}最多只能选择${maxCount}个`);

          // 通知父组件恢复为旧值
          emit("update:value", { ...oldDataValue.value });
          emit("change", { ...oldDataValue.value });
          return;
        }
      }
    }

    // 验证通过后，保存当前值作为旧值
    oldDataValue.value = { ...dataValue.value };

    // 触发更新事件
    const updatedValue = { ...dataValue.value };
    emit("update:value", updatedValue);
    emit("change", updatedValue);
  };

  watch(
    () => props.table,
    () => initValue(props.value),
    { deep: true }
  );
  watch(
    () => props.multiple,
    () => {
      initValue(props.value);
    }
  );

  watch(
    () => props.value,
    (newVal, oldVal) => {
      // 只有当新值和当前值不同时才更新
      if (JSON.stringify(newVal) !== JSON.stringify(dataValue.value)) {
        initValue(newVal);
      }
    },
    { deep: true }
  );

  onMounted(() => {
    initValue(props.value);
  });

  const getTableRows = computed(() => {
    return props.table.rows;
  });

  return {
    dataValue,
    handleChange,
    getTableRows
  };
}
